﻿using System;
using System.IO;
using System.Web.UI;


namespace JYH.Framework
{
    /// <summary>
    /// 压缩ViewState
    /// </summary>
    public class ViewStateCompressPage : System.Web.UI.Page
    {
        private const string HiddenFieldName = "__COMPRESSSTATE";

        protected override void SavePageStateToPersistenceMedium(object state)
        {
            LosFormatter mFormat = new LosFormatter();
            using (StringWriter mWriter = new StringWriter())
            {
                mFormat.Serialize(mWriter, state);
                var mViewStateStr = mWriter.ToString();
                byte[] pBytes = System.Convert.FromBase64String(mViewStateStr);
                pBytes = Zip.Compress(pBytes);
                var vStateStr = System.Convert.ToBase64String(pBytes);
                ClientScript.RegisterHiddenField(HiddenFieldName, vStateStr);
            }
        }

        protected override object LoadPageStateFromPersistenceMedium()
        {
            String vState = this.Request.Form.Get(HiddenFieldName);
            byte[] pBytes = System.Convert.FromBase64String(vState);
            pBytes = Zip.DeCompress(pBytes);
            LosFormatter mFormat = new LosFormatter();
            return mFormat.Deserialize(System.Convert.ToBase64String(pBytes));
        }

        protected override void OnPreLoad(EventArgs e)
        {
            //  CheckCopyRight(); //验证版权，可根据实际情况确定是否启用

            base.OnPreLoad(e);
        }

        private bool isValidCopyRight = true;
        /// <summary>
        /// 是否验证版权
        /// </summary>
        protected virtual bool IsValidCopyRight
        {
            get
            {
                return isValidCopyRight;
            }
            set { isValidCopyRight = value; }
        }

        private const string DRP_COPYRIGHT_KEY = "DRP_COPYRIGHT_KEY";

        private void CheckCopyRight()
        {
            if (!IsValidCopyRight) return;
            var isChecked = CacheHelper<String>.Get(DRP_COPYRIGHT_KEY);
            if (isChecked == null)
            {
                isChecked = ValidCopyRight() ? "1" : "0";
                CacheHelper<string>.Insert(DRP_COPYRIGHT_KEY, isChecked);
            }
            if (isChecked == "0")
                throw new FormatException("授权文件不合法");
        }

        private bool ValidCopyRight()
        {
            var isChecked = false;
            var __file = System.AppDomain.CurrentDomain.BaseDirectory + "\\Bin\\DRPLICENSE.LIC";
            if (!File.Exists(__file))
                throw new FileNotFoundException("未找到授权文件");
            var text = FileHelper.OpenText(__file);
            if (string.IsNullOrEmpty(text))
                throw new FormatException("授权文件不合法");
            var arr = new string[5];
            try
            {
                var buffer = Convert.FromBase64String(text);
                var s = System.Text.ASCIIEncoding.UTF8.GetString(buffer);
                s = Security.Decrypt(s); //解密
                arr = s.Split('@');
                if (arr[0].Equals("-1")) //无期限
                    return true;
            }
            catch
            {
                throw new FormatException("授权文件不合法");
            }
            var date = Convert.ToDateTime(arr[1]);
            if (date <= DateTime.Now)
                isChecked = false;
            else
                isChecked = true;
            return isChecked;
        }

        /// <summary>
        /// 读取授权文件
        /// </summary>
        /// <returns></returns>
        protected string ReadLicense()
        {
            try
            {
                var __file = System.AppDomain.CurrentDomain.BaseDirectory + "\\Bin\\DRPLICENSE.LIC";
                var text = FileHelper.OpenText(__file);
                var buffer = Convert.FromBase64String(text);
                var s = System.Text.ASCIIEncoding.UTF8.GetString(buffer);
                s = Security.Decrypt(s); //解密
                var arr = new string[5];
                arr = s.Split('@');
                var outArr = new string[5];
                outArr[0] = "版本号：" + arr[0];
                outArr[1] = "使用有效期：" + (arr[1] == "-1" ? "永久" : arr[1]);
                outArr[2] = "授权公司名称：" + arr[2];
                outArr[3] = "软件使用说明：" + arr[3];
                return string.Join("<br />", outArr);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
